/**
 * 报警管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>报警管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true"  class="user-search">
      <el-form-item label="快速开始：">
        <el-select size="small" v-model="dateDefaultSelect" placeholder="请选择" @change="changeDate">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间：">
           <el-date-picker
                v-model="searchParm.startDate"
                type="date"
                :disabled = "disabled"
                placeholder="选择日期">
            </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间：">
          <el-date-picker
                v-model="searchParm.endDate"
                type="date"
                :disabled="disabled"
                placeholder="选择日期">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="模糊搜索：">
          <el-input size="small" v-model="searchParm.alarmTip" placeholder="报警详情"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary"  @click="batchAckAlarm">批量确认</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :row-key="getRowKey" @selection-change="handleSelectionChange" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <!-- <el-table-column align="center" type="selection" width="60">
      </el-table-column> -->
      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
      <el-table-column sortable prop="alarmId" label="报警ID" width="100">
      </el-table-column>
      <el-table-column  prop="alarmTime" label="报警时间" width="150">
      </el-table-column>
      <el-table-column  prop="projectName"  width="200">
        <template slot="header" slot-scope="scope">
        <el-select size="small" v-model="searchParm.projectId" placeholder="请选择" @change="search">
          <el-option
            v-for="item in project_option"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      </el-table-column>
      <el-table-column  prop="boxName" width="150">
        <template slot="header" slot-scope="scope">
        <el-select size="small" v-model="searchParm.boxId" placeholder="请选择" @change="search">
          <el-option
            v-for="item in boxList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      </el-table-column>
      <el-table-column  prop="alarmTip" label="报警详情" width="300" :show-overflow-tooltip="true">
      </el-table-column>
   
      <el-table-column  prop="serious"  width="120" :formatter="randerSerious">
        <template slot="header" slot-scope="scope">
         <el-select size="small" v-model="searchParm.serious" placeholder="请选择" @change="search">
          <el-option
            v-for="item in serious_option"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="ackAlarm(scope.$index, scope.row)">确认</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <el-dialog :title="dialoagTitle" :visible.sync="dialogVisible" width="30%" @click="closeDialog">
      <span>{{title}}</span>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="ack">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '../../components/Pagination'
import {getProjectList,getAlarmList, getBoxList,updateAlarmWarning} from '../../api/alarmMgr'
export default {
  data() {
    return {
      dateDefaultSelect:0,
      disabled: true,
      loading: false, //是显示加载
      dialoagTitle:'提示',
      title:'',
      dialogVisible:false,
      searchParm:{
        startDate:'',
        endDate:'',
        alarmTip:'',
        projectId:0,
        boxId:0,
        serious:0,
        page:1,
        limit:10
      },
      listData:[],
      
      
      options: [{
          value: 0,
          label: '全部'
        }, {
          value: 1,
          label: '今天'
        },{
            value: 2,
            label: '昨天'
        },{
            value: 3,
            label: '最近七天'
        },{
            value: 4,
            label: '本月'
        },{
            value: 5,
            label: '上月'
        },{
            value: 6,
            label: '自定义'
        },
        ],

      project_option:[
        {
          value:0,
          label: '项目名称'
        }
      ],



      serious_option:[
        {
          value:0,
          label:'严重性'
        },{
          value:1,
          label:'一般',
        },{
          value:2,
          label:'重要',
        },{
          value:3,
          label:'紧急',
        }
      ],
   
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      multipleSelection:[],
      batchPassArr:[],
      dialogParam:{
        id:'',
        ids:'',
        single:true
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },


  /**
   * 创建完毕
   */
  created() {
    //获取数据
    this.getProject();
    this.search();
  },

  mounted(){
  },

  destroyed: function () { // 离开页面生命周期函数
    
  },
  computed:{
    boxList:function(){
      const param = {
        projectId:this.searchParm.projectId
      };
      var box_option = [{
        value:0,
        label:'全部BOX'
      }];
      getBoxList(param).then(
        res => {
          if (res.data.success == false) {
            this.$message({
              type: 'info',
              message: res.data.message
            })
          }else{
            let detailsList = res.data.result
            for (const i in detailsList) {
              box_option.push({
                value:detailsList[i].id,
                label:detailsList[i].boxName
              });  
            }
        }
        }
      ).catch(err => {
          this.$message.error('获取BOX列表失败，请稍后再试！')
        });
        return box_option;
    }
  },


  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    search:function(){
      this.loading = true;
      this.searchParm.page = 1;
      const param = {};
      Object.assign(param,this.searchParm)
      if(param.startDate != '' && param.endDate != ''){
        param.startDate = this.dateFormat("YYYY-mm-dd", param.startDate);
        param.endDate = this.dateFormat("YYYY-mm-dd", param.endDate);
          param.startDate += ' 00:00:00';
          param.endDate  += ' 23:59:59'; 
      }
      console.log('param',param);
      getAlarmList(param)
        .then(res => {
          console.log("res",res)
          this.loading = false
          if (res.data.success == false) {
            this.$message({
              type: 'info',
              message: res.data.message
            })
          } else {
            this.listData = res.data.result.list
            // 分页赋值
            this.pageparm.currentPage = this.searchParm.page
            this.pageparm.pageSize = this.searchParm.limit
            this.pageparm.total = res.data.result.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取报警列表失败，请稍后再试！')
        })
    },
  
    getProject(){
      getProjectList({}).then(res=>{
          console.log("res",res)
          if (res.data.success == false) {
            this.$message({
              type: 'info',
              message: res.data.message
            })
          }else{
            let detailsList = res.data.result
            for (const i in detailsList) {
              this.project_option.push({
                value:detailsList[i].id,
                label:detailsList[i].name
              });  
            
            }
            console.log('option',this.project_option);
          }
      }).catch(err => {
          this.$message.error('获取项目列表失败，请稍后再试！')
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    changeDate:function(){
      if(this.dateDefaultSelect == 0){ //全部
        this.disabled = true;
        this.searchParm.startDate = '';
        this.searchParm.endDate = '';
      }else {
        this.disabled = false;
        var now = new Date(); //当前日期  
        var nowDayOfWeek = now.getDay(); //今天本周的第几天  
        var nowDay = now.getDate(); //当前日 
        var nowMonth = now.getMonth(); //当前月  
        var nowYear = now.getFullYear(); 
        var lastMonthDate = new Date(); //上月日期  
        lastMonthDate.setDate(1);  
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        if(this.dateDefaultSelect == 1){ //今天
            this.searchParm.startDate =  new Date();
            this.searchParm.endDate = new Date();
        }else if(this.dateDefaultSelect == 2){ //昨天
            this.filterTime(1);
            this.searchParm.endDate = this.searchParm.startDate;
        }else if(this.dateDefaultSelect ==3 ){ //最近7天
            this.filterTime(6);
        }else if(this.dateDefaultSelect ===4 ){ //本月
            this.searchParm.startDate = new Date(nowYear, nowMonth, 1);
            this.searchParm.endDate = new Date(nowYear, nowMonth, this.getMonthDays(nowYear,nowMonth));  
        }else if(this.dateDefaultSelect ==5 ){ //上个月
           let lastMounthYear = lastMonthDate.getFullYear();
           let lastMounth = lastMonthDate.getMonth();
           this.searchParm.startDate = lastMonthDate; 
           this.searchParm.endDate = new Date(lastMounthYear,lastMounth,this.getMonthDays(lastMounthYear,lastMounth));
        }else{ //自定义
          this.searchParm.startDate = '';
          this.searchParm.endDate = '';
        }
      }
    },
    getMonthDays:function(nowYear,myMonth) {  
        let monthStartDate = new Date(nowYear, myMonth, 1);  
        let monthEndDate = new Date(nowYear, myMonth + 1, 1);  
        let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);  
        return days;  
    },

    filterTime:function(interval) {
      if (interval !== -1) {
          const end = new Date();
          const time = end.getTime() - interval * 24 * 60 * 60 * 1000;
          this.searchParm.startDate = new Date(time);
          this.searchParm.endDate = end;
      } else {
          this.searchParm.startDate = '';
          this.searchParm.endDate = '';
      }
    },
     getRowKey (row) {
      return row.id
    },
    batchAckAlarm:function(){
      if(this.batchPassArr.length == 0){
        this.$message.error('请选中一条报警记录');
      }else{
        this.dialogVisible = true;
        this.title = '是否要批量确认?';
        this.dialogParam.single =false;
      }
    },
    ackAlarm:function(index,row){
      if (row != undefined && row != 'undefined'){
        this.dialogVisible = true;
        this.title = '是否要确认此报警?';
        this.dialogParam.id = row.id;
        this.dialogParam.single = true;
      }
    },
    ack:function(){
        let ids = '';
        if(this.dialogParam.single){
          ids = this.dialogParam.id;
        }else{
          ids = this.dialogParam.ids;
        }
        console.log('ids ajax',ids);
        updateAlarmWarning(ids).then(()=>{
          this.dialogVisible = false;
          this.search();
        }).catch(err => {
          this.$message.error('报警确认失败，请稍后再试！')
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.batchPassArr= []; //每次点击需清空原本数组的内容
      this.multipleSelection.map(item => { //遍历数组，把id存进自定义的数组里
        this.batchPassArr.push(item.id);
      })
      this.dialogParam.ids = this.batchPassArr.join(','); 
    },
     // 关闭弹出框
    closeDialog() {
      this.dialogVisible = false;
    },
    randerSerious(row, column, cellValue){
      let res = '';
      if(cellValue == 1){
        res = '一般';
      }else if(cellValue == 2){
        res = '重要';
      }else if(cellValue == 3){
        res = '紧急';
      }
      return res;
    },
    dateFormat(fmt, date) {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
        };
        return fmt;
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 
 